/* 
rabbitmq 消息队列 封装发送信息和处理接收信息操作(回调方式,后期采取-异步方式)
*/


const amqp = require('amqplib/callback_api');
const moment = require('moment')
const fs = require('fs')

/* 发送 */
const raSend = () => {
    return new Promise((resolve, reject) => {
        amqp.connect('amqp://localhost:5673', function (error0, connection) {
            if (error0) {
                throw error0;
            }
            var times = moment().format('YYYY-MM-DD')
            var msgName = 'wangs' + times
            connection.createChannel(function (error1, channel) {
                if (error1) {
                    throw error1;
                }
                var queue = msgName;
                var msg = 'new msg notice!';
                channel.assertQueue(queue, {
                    durable: false
                });
                channel.sendToQueue(queue, Buffer.from(msg));
                resolve(true)
            });
        });
    })
}

/* 接收 */
const receFun = (fun, req) => {
    return new Promise((resolve, reject) => {
        amqp.connect('amqp://localhost:5673', function (error0, connection) {
            if (error0) {
                throw error0;
            }
            connection.createChannel(function (error1, channel) {
                if (error1) {
                    throw error1;
                }
                //暂时定义queue为这个
                var queue = 'wangs2025-07-03';
                channel.assertQueue(queue, {
                    durable: false
                });
                channel.consume(queue, function (msg) {
                    /* 接受到消息对应处理操作*/
                    // console.log(" [x] Received %s", msg.content.toString());
                    if (msg.content.toString() == 'new msg notice!') {
                        fun(req)
                        resolve(msg.content.toString())
                    }
                }, {
                    //noAck表示自动确认消息 true为自动 false为手动
                    noAck: true
                });
            });
        });
    })
}


module.exports = {
    raSend,
    receFun
}